﻿using System;
using System.Linq;
using System.Windows.Forms;
using QD_Clients.Code.DbContent;
using QD_Clients.Models;
using System.IO;
using QD.Tools;
using QD.SQLHelper;
using System.Net;
using System.ServiceProcess;
using System.Collections.Generic;

namespace QD_Clients
{
    public partial class Login : Form
    {
        /// <summary>
        /// 记录所有历史登录的信息文件路径
        /// </summary>
        private string pwdFilePath;

        /// <summary>
        /// 记录上次登录的账户信息文件路径
        /// </summary>
        private string logonFilePath;
        public Login()
        {
            InitializeComponent();

            this.ControlBox = false;
            this.StartPosition = FormStartPosition.CenterScreen;
            this.FormBorderStyle = FormBorderStyle.FixedSingle; //不可以拖动改变大小

            string rootPath = System.AppDomain.CurrentDomain.BaseDirectory;
            pwdFilePath = Path.Combine(rootPath, "QD_Clients.txt");
            logonFilePath = Path.Combine(rootPath, "QD_Clients_Logon.txt");
        }

        private void Login_Load(object sender, EventArgs e)
        {
            Source_DataBindByLocal();

            AutoLogonMes();

            this.AcceptButton = this.button1;
            this.CancelButton = this.button2;
            this.Shown += Login_Shown;
        }

        private void Login_Shown(object sender, EventArgs e)
        {
            this.txtQDPwd.Focus();
        }

        //加载本地sql实例
        private void Source_DataBindByLocal()
        {
            string HostName = Dns.GetHostName();
            ServiceController[] services = ServiceController.GetServices();
            List<string> list = new List<string>();

            foreach (ServiceController s in services)
            {
                if (s.ServiceName.ToLower() == "mssqlserver")
                {
                    list.Add(HostName);
                }
                else if (s.ServiceName.ToLower().IndexOf("mssql$") != -1)
                {
                    list.Add(HostName + "\\" + s.ServiceName.Substring(s.ServiceName.IndexOf("$") + 1));
                }
            }

            //加载历史记录
            string pwds = FileHelper.ReadFromTxt(pwdFilePath);
            string[] strs = pwds.Split(new string[] { "\r\n" }, StringSplitOptions.RemoveEmptyEntries);

            foreach (string str in strs)
            {
                string[] pwd = str.Split(new string[] { " " }, StringSplitOptions.RemoveEmptyEntries);
                if (pwd.Length == 3)
                {
                    if (!list.Contains(pwd[0]))
                    {
                        list.Add(pwd[0]);
                    }
                }
            }

            this.cbSource.DataSource = list;
            this.cbSource.SelectedIndex = this.cbSource.Items.IndexOf(HostName);
        }
        private void AutoUidPwd()
        {
            string pwds = FileHelper.ReadFromTxt(pwdFilePath);
            string[] strs = pwds.Split(new string[] { "\r\n" }, StringSplitOptions.RemoveEmptyEntries);
            string[] pwd;

            bool isauto = false;
            foreach (string str in strs)
            {
                if (str.Contains(this.cbSource.Text) && this.cbsecurity.Text != "")
                {
                    pwd = str.Split(new string[] { " " }, StringSplitOptions.RemoveEmptyEntries);
                    this.txtUID.Text = pwd[1].ToString();
                    this.txtPWD.Text = pwd[2].ToString();
                    isauto = true;
                    this.rembDbMes.Checked = true;
                }
            }

            if (!isauto)
            {
                this.txtUID.Text = this.txtPWD.Text = "";
            }
        }
        private void AutoLogonMes()
        {
            if (FileHelper.Exists(logonFilePath))
            {
                string logonMes = FileHelper.ReadFromTxt(logonFilePath);
                if (logonMes.Length > 0)
                {
                    string[] mes = logonMes.Split(new string[] { " " }, StringSplitOptions.RemoveEmptyEntries);
                    this.cbSource.Text = mes[0];
                    if (mes[1] == "2")
                    {
                        this.cbsecurity.SelectedIndex = 1;
                        this.txtUID.Text = mes[2];
                        this.txtPWD.Text = mes[3];
                    }

                    if (mes.Length == 5)
                    {
                        this.txtQDUid.Text = mes[4];
                    }
                }
                this.rembLoginMes.Checked = true;
            }
        }
        private void button1_Click(object sender, EventArgs e)
        {
            try
            {
                string _qdUid = this.txtQDUid.Text.Trim();
                string _qdPwd = this.txtQDPwd.Text.Trim();
                string _cbSource = this.cbSource.Text;
                string _uid = this.txtUID.Text.Trim();
                string _pwd = this.txtPWD.Text.Trim();
                int _logonType = 0;

                if (string.IsNullOrEmpty(_qdUid))
                {
                    PromptHelper.Prompt("请输入平台登录用户名！");
                    return;
                }
                else if (string.IsNullOrEmpty(_qdPwd))
                {
                    PromptHelper.Prompt("请输入平台登录密码！");
                    return;
                }

                if (this.cbsecurity.Text == "SQL Server 身份证验")
                {
                    _logonType = 2;
                }
                else
                {
                    _logonType = 1;
                }

                bool isOk = QDUserHelper.LoginDb(_qdUid, _qdPwd.ToMD5Encryption(), _cbSource, _uid, _pwd, _logonType);

                if (isOk)
                {
                    if (DbConfig.Instance.LogonConfig.LogonType == 2 && this.rembDbMes.Checked)
                    {
                        string str = FileHelper.ReadFromTxt(pwdFilePath);
                        string newpwd = DbConfig.Instance.LogonConfig.ServerName + " " + DbConfig.Instance.LogonConfig.UserID + " " + DbConfig.Instance.LogonConfig.PassWord;

                        if (!str.Contains(newpwd))
                        {
                            FileHelper.AppendToTxt(pwdFilePath, newpwd);
                        }
                    }

                    if (this.rembLoginMes.Checked)
                    {
                        string logonMes = DbConfig.Instance.LogonConfig.ServerName + " " + DbConfig.Instance.LogonConfig.LogonType + " " + DbConfig.Instance.LogonConfig.UserID + " " + DbConfig.Instance.LogonConfig.PassWord + " " + _qdUid;
                        FileHelper.AddToTxt(logonFilePath, logonMes);
                    }

                    QDClientsPlat frm = new QDClientsPlat();
                    this.Hide();
                    frm.Show();
                }
            }
            catch (Exception ex)
            {
                PromptHelper.Prompt(ex);
            }
        }

        //private void login(string qdUid, string qdPwd)
        //{
        //    MSDbContext db = new MSDbContext(BasicSetting.SQL_CONN_STR);
        //    if (string.IsNullOrEmpty(qdUid))
        //    {
        //        PromptHelper.Prompt("请输入用户名！");
        //    }
        //    else if (string.IsNullOrEmpty(qdPwd))
        //    {
        //        PromptHelper.Prompt("请输入密码！");
        //    }
        //    else
        //    {
        //        QDResources dbPlat = new QDResources();
        //        QDUser user = dbPlat.QDUser.FirstOrDefault(p => p.Uid == qdUid);
        //        if (user == null || user.Pwd != qdPwd.ToMD5Encryption())
        //        {
        //            PromptHelper.Prompt("用户名或密码错误！");
        //        }
        //        else if (user.IsDimission)
        //        {
        //            PromptHelper.Prompt("该员工已离职！");
        //        }
        //        else if (user.IsForbidLogon)
        //        {
        //            PromptHelper.Prompt("该账号禁止登录！");
        //        }
        //        else
        //        {
        //            if (this.rembLoginMes.Checked)
        //            {
        //                string logonMes = qdUid + " " + qdPwd;
        //                FileHelper.AddToTxt(logonFilePath, logonMes);
        //            }

        //            QDUserHelper.CurUser = user;
        //            QDClientsPlat frm = new QDClientsPlat();
        //            this.Hide();
        //            frm.Show();
        //        }
        //    }
        //}

        private void button2_Click(object sender, EventArgs e)
        {
            Application.Exit();
        }


        private void linkLabel1_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            if (MessageBox.Show("确定删除所有保存的密码？", "", MessageBoxButtons.OKCancel) == DialogResult.OK)
            {
                File.Delete(pwdFilePath);
                MessageBox.Show("删除成功！");
            }
        }

        private void cbSource_TextChanged(object sender, EventArgs e)
        {
            AutoUidPwd();
        }
    }
}
